#pragma once
// -------------------------------------------------
// ZED Kit
// -------------------------------------------------
//   File Name: ns_wrappers.hpp
//      Author: Ziming Li
//     Created: 2022-09-22
// -------------------------------------------------
// Copyright (C) 2022 MingYang Software Technology.
// -------------------------------------------------

#ifndef ZED_APPLE_NS_WRAPPERS_HPP
#define ZED_APPLE_NS_WRAPPERS_HPP

#include <Foundation/Foundation.h>
#include "../memory.hpp"

namespace zed {

struct ns_object_finalizer {
    void operator()(NSObject *o) const {
#if !__has_feature(objc_arc)
        [o release];
#endif
    }
};

template <class T>
class ns_object : public unique_resource<T *, ns_object_finalizer>
{
protected:
    ns_object(T *o) : unique_resource<T *, ns_object_finalizer>(o) {}
};

template <class T>
class unique_ns_object final : public ns_object<T>
{
public:
    unique_ns_object(T *o) : ns_object<T>(o) {}
};

class ns_string : public ns_object<NSString>
{
public:
    explicit ns_string(const char *psz, NSStringEncoding encoding = NSUTF8StringEncoding);
private:
    static NSString* string_with_cstring(const char *psz, NSStringEncoding encoding);
};

class ns_url : public ns_object<NSURL>
{
public:
    explicit ns_url(const char *psz);
private:
    static NSURL* url_with_cstring(const char *psz);
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Implementations

ns_string::ns_string(const char *psz, NSStringEncoding encoding)
    : ns_object<NSString>(string_with_cstring(psz, encoding))
{
}

NSString* ns_string::string_with_cstring(const char *psz, NSStringEncoding encoding)
{
    return [[NSString alloc] initWithCString: psz encoding: encoding];
}

ns_url::ns_url(const char *psz) : ns_object<NSURL>(url_with_cstring(psz))
{
}

NSURL* ns_url::url_with_cstring(const char *psz)
{
    ns_string s(psz);
    return [[NSURL alloc] initWithString: s.get()];
}

} // namespace zed

#endif // ZED_APPLE_NS_WRAPPERS_HPP
